package com.huijz.flywaydemo.migration;

import org.flywaydb.core.api.migration.BaseJavaMigration;
import org.flywaydb.core.api.migration.Context;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.SingleConnectionDataSource;

/**
 * 演示：基于Java的迁移
 * 版本号为V7，描述为"Add_user_preferences"
 */
public class JavaBasedMigration extends BaseJavaMigration {

    @Override
    public void migrate(Context context) throws Exception {
        JdbcTemplate jdbcTemplate = getJdbcTemplate(context);

        // 插入一些示例数据
        jdbcTemplate.update(
                "INSERT INTO user_preferences (user_id, preference_key, preference_value) VALUES (?, ?, ?)",
                1, "theme", "dark");
        jdbcTemplate.update(
                "INSERT INTO user_preferences (user_id, preference_key, preference_value) VALUES (?, ?, ?)",
                1, "notifications", "enabled");
        jdbcTemplate.update(
                "INSERT INTO user_preferences (user_id, preference_key, preference_value) VALUES (?, ?, ?)",
                2, "theme", "light");
    }

    private static JdbcTemplate getJdbcTemplate(Context context) {
        JdbcTemplate jdbcTemplate = new JdbcTemplate(
                new SingleConnectionDataSource(context.getConnection(), true));

        // 创建用户偏好表
        jdbcTemplate.execute("CREATE TABLE user_preferences (" +
                "id BIGINT AUTO_INCREMENT PRIMARY KEY, " +
                "user_id BIGINT NOT NULL, " +
                "preference_key VARCHAR(50) NOT NULL, " +
                "preference_value VARCHAR(255), " +
                "FOREIGN KEY (user_id) REFERENCES users(id), " +
                "UNIQUE KEY unique_user_preference (user_id, preference_key)" +
                ")");
        return jdbcTemplate;
    }
}